#! /bin/bash

set -e

function main () {
  local readonly instance_id=${1:?missing parameter instance id};
  while true; do
    local res=$(vultr-cli instance get $instance_id);

    local ip_addr=$(echo "$res" | awk ' /^MAIN IP/ { print $(NF); exit; }');
    local status=$(echo "$res" | awk ' /^STATUS/ { print $(NF); exit; }');
    local server_state=$(echo "$res" | awk ' /^SERVER STATE/ { print $(NF); exit; }');
    

    if [ "$ip_addr" != '0.0.0.0' ] && [ "$status" = 'active' ] && [ "$server_state" = 'ok' ]; then
      echo $ip_addr;
      exit;
    else
      sleep 10;
    fi
  done;
}

main $@;

